/**
  * @file	M24C02.c
  *	@author	yoyoyes
  * @date	2023-6-6
  */
  
#include "M24C02.h"
#include "iic.h"

/**
  * @func	M24C02_init
  * @param	none
  * @return	none
  */
void M24C02_init(void)
{
	iic_init();
}

/**
  * @func	M24C02_write_byte
  * @param	none
  * @return	none
  */
uint8_t M24C02_write_byte(uint8_t addr, uint8_t byte)
{
	iic_start();
	
	/* 发送命令 */
	iic_send_byte(M24C02_WRITE_ADDR);
	if(iic_wait_ack(100) != 0)
	{
		return 1;
	}
	/* 发送地址 */
	iic_send_byte(addr);
	if(iic_wait_ack(100) != 0)
	{
		return 2;
	}
	/* 发送数据 */
	iic_send_byte(byte);
	if(iic_wait_ack(100) != 0)
	{
		return 3;
	}
	
	iic_stop();
	
	return 0;
}

/**
  * @func	M24C02_write_page
  * @param	none
  * @return	none
  */
uint8_t M24C02_write_page(uint8_t addr, uint8_t *byte)
{
	uint8_t i;
	
	iic_start();
	
	/* 发送命令 */
	iic_send_byte(M24C02_WRITE_ADDR);
	if(iic_wait_ack(100) != 0)
	{
		return 1;
	}
	/* 发送地址 */
	iic_send_byte(addr);
	if(iic_wait_ack(100) != 0)
	{
		return 2;
	}
	/* 发送数据 */
	for(i = 0; i < 16; i++)
	{
		iic_send_byte(byte[i]);
		if(iic_wait_ack(100) != 0)
		{
			return 3 + i;
		}
	}
	
	iic_stop();
	
	return 0;
}

/**
  * @func	M24C02_write_page
  * @param	none
  * @return	none
  */
uint8_t M24C02_read_byte(uint8_t addr, uint8_t *byte, uint16_t len)
{
	uint8_t i;
	
	iic_start();
	
	/* 发送命令 */
	iic_send_byte(M24C02_WRITE_ADDR);
	if(iic_wait_ack(100) != 0)
	{
		return 1;
	}
	/* 发送地址 */
	iic_send_byte(addr);
	if(iic_wait_ack(100) != 0)
	{
		return 2;
	}
	
	iic_start();
	
	/* 发送命令 */
	iic_send_byte(M24C02_READ_ADDR);
	if(iic_wait_ack(100) != 0)
	{
		return 3;
	}
	
	for(i = 0; i < len - 1; i++)
	{
		byte[i] = iic_read_byte(1);
	}
	
	byte[len - 1] = iic_read_byte(0);
	
	iic_stop();
	
	return 0;
}


